// pages/turntable/index.js
const Page = require('../../../utils/ald-stat.js').Page;
const app = getApp();
let interstitialAd = null;
Page({

  /**
   * 页面的初始数据
   */
  awardsConfig: {
    awards: [{
        "index": 0,
        "name": '谢谢参与',
        "img": '../../../imgs/zhuanwu.png'
      },
      {
        "index": 1,
        "name": '3热力币',
        "img": '../../../imgs/zhuanbi.png'
      },
      {
        "index": 2,
        "name": '5热力币',
        "img": '../../../imgs/zhuanbi.png'
      },
      {
        "index": 3,
        "name": '10热力币',
        "img": '../../../imgs/zhuanbi.png'
      },
      {
        "index": 4,
        "name": '20热力币',
        "img": '../../../imgs/zhuanbi.png'
      },
      {
        "index": 5,
        "name": '5元',
        "img": '../../../imgs/zhuanred.png'
      },
      {
        "index": 6,
        "name": '10元',
        "img": '../../../imgs/zhuanred.png'
      },
      {
        "index": 7,
        "name": '20元',
        "img": '../../../imgs/zhuanred.png'
      },
      {
        "index": 8,
        "name": '天猫精灵',
        "img": '../../../imgs/zhuantm.png'
      },
      {
        "index": 9,
        "name": 'iPhone XS',
        "img": '../../../imgs/zhuanxs.png'
      },
    ]
  },
  data: {
    tryfail: true,
    winner: '',
    losedialog: true,
    windialog: true,
    record: '',
    awardsList: [],
    animationData: {},
    awardIndex: '',
    chance_count: '',
    disabled: false,
    button_state: 2,
    nochance: true,
    ad_auth: false,
    ad_data: {},
    number: '',
    clickedfail: true,
    erweima: '',
    flow: false, //防止流量主广告点击回来出弹框
    freechou: true,
    free: '',
    currency: true,
    code: '',
    home_content:true,
  },
  /**
   * 生命周期函数--监听页面加载
   */

  onLoad: function(options) {
    const that = this;
    that.drawAwardRoundel();
    if(options.home==1){
      var object = {
        unionid: wx.getStorageSync('openid'),
        type:22
      }
      var signs = app.sort_ASCII(object)
      wx.request({
        url: app.globalData.new_url + '/redpacket/Theme/activity_reward',
        data: {
          unionid: wx.getStorageSync('openid'),
          type:22,
          sign: signs
        },
        method: 'POST',
        header: {
          'Cache-Control': 'max-age=60,public', //60秒
        },
        success: function (res) {
          if (res.data.code === 200) {
            that.setData({
              windialog:false,
              winner: res.data.tc_reward,
              home_content:false,
            })
          }
        }
      })
    }
    if (options.erweima) {
      that.data.erweima = options.erweima
    }
    if (wx.createInterstitialAd) {
      interstitialAd = wx.createInterstitialAd({
        adUnitId: 'adunit-f51c06c09f759c90'
      })
      interstitialAd.onError((err) => {
        console.log('onError event emit', err)
      })
    } else {
      wx.showModal({
        title: '提示',
        content: '当前微信版本过低，无法使用该功能，请升级到最新微信版本后重试。'
      })
    }
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {
    const that = this;
    if(that.data.erweima == 2) {
      that.setData({
        clickedfail: true,
        tryfail: false,
      })
      that.data.erweima = 0
    }
    if (app.globalData.scene === 1038 && that.data.flow) {
      var object = {
        unionid: wx.getStorageSync('openid'),
        type: 2,
        ad_id: that.data.ad_auth,
        plate: 5,
      }
      var sign = app.sort_ASCII(object)
      wx.request({
        url: app.globalData.new_url + '/adauth/Adv/back_adv',
        data: {
          unionid: wx.getStorageSync('openid'),
          type: 2,
          ad_id: that.data.ad_auth,
          plate: 5,
          sign:sign
        },
        method: 'POST',
        header: {
          'Cache-Control': 'max-age=60,public', //60秒
        },
        success: function(res) {
          console.log(res.data.msg, res)
          app.globalData.scene = 1001;
          that.data.erweima = 0;
          if (res.data.code===200) {
            
          } else {
            that.setData({
              tryfail: false,
              clickedfail: true
            })
          }
        }
      })
    }
    var object = {
      unionid: wx.getStorageSync('openid'),
    }
    var signs = app.sort_ASCII(object)
    wx.request({
      url: app.globalData.new_url + '/luck/luck/get_state',
      data: {
        unionid: wx.getStorageSync('openid'),
        sign: signs
      },
      method: 'POST',
      header: {
        'Cache-Control': 'max-age=60,public', //60秒
      },
      success: function(res) {
        console.log(res)
        if (res.data.code === 400) {
          that.setData({
            code: res.data.code,
            record: res.data.content.turntable_jl,
            chance_count: res.data.msg,
          })
        } else {
          that.setData({
            ad_auth: res.data.ad_auth,
            currency: res.data.currency,
            record: res.data.content.turntable_jl,
            chance_count: res.data.msg,
            free: res.data.free
          })
        }
      }
    })
  },
 
  goindex: function () {
    let pages = getCurrentPages();
    let prevPage = pages[0]
    if (prevPage.route == "pages/tarbar/index/index") {
      prevPage.setData({
        isShowInterstitialAd: 100,
      })
    }
    wx.switchTab({
      url: '/pages/tarbar/index/index',
    })
  },
  //画抽奖转盘
  drawAwardRoundel: function() {
    const that = this;
    var awards = that.awardsConfig.awards;
    var awardsList = [];
    var turnNum = 1 / awards.length;
    for (var i = 0; i < awards.length; i++) {
      awardsList.push({
        turn: i * turnNum + 'turn',
        lineTurn: i * turnNum + turnNum / 2 + 'turn',
        award: awards[i].name,
        awards: awards[i].img
      });
    }
    that.setData({
      awardsList: awardsList
    })
  },
  goplayReward: function(e) {
    const type = e.target.dataset.type;
    const that = this;
    that.setData({
      freechou: true,
      disabled: true,
    }, () => {
      var object = {
        unionid: wx.getStorageSync('openid'),
        type: type
      }
      var sign = app.sort_ASCII(object)
      wx.request({
        url: app.globalData.new_url + '/luck/luck/index',
        data: {
          type: type,
          unionid: wx.getStorageSync('openid'),
          sign: sign
        },
        method: 'POST',
        header: {
          'content-type': 'application/json'
        },
        success: function(res) {
          console.log(res)
          var awardIndex = res.data.content.lindex - 1;
          console.log(awardIndex)
          var runNum = 7; //转的圈数
          //旋转角度
          that.runDeg = that.runDeg || 0;
          that.runDeg = that.runDeg + (360 - that.runDeg % 360) + (360 * runNum - awardIndex * (360 / 10))
          //创建动画
          var animationRun = wx.createAnimation({
            duration: 4000,
            timingFunction: 'ease'
          })
          animationRun.rotate(that.runDeg).step();
          that.setData({
            animationData: animationRun.export(),
          })
          //中奖提示
          var awardsConfig = that.awardsConfig;
          setTimeout(function() {
            if (awardIndex == 0) {
              that.setData({
                losedialog: false,
              })
            } else {
              that.setData({
                windialog: false,
                winner: awardsConfig.awards[awardIndex].name,
                home_content:true
              })
            }
          }.bind(this), 4000)
        }
      })
    })
  },
  //发起抽奖
  playReward: function(e) {
    const type = e.target.dataset.type;
    const that = this;
    if (that.data.ad_auth) {
      that.setData({
        freechou: false,
      })
    } else if (!that.data.currency) {
      wx.showModal({
        title: '提示',
        content: '热力币不足',
        showCancel: false,
      })
    } else {
      that.setData({
        disabled: true,
      }, () => {
        wx.showModal({
          title: '提示',
          content: '消耗3热力币抽奖',
          success(res) {
            if (res.confirm) {
              var object = {
                unionid: wx.getStorageSync('openid'),
                type: type
              }
              var sign = app.sort_ASCII(object)
              wx.request({
                url: app.globalData.new_url + '/luck/luck/index',
                data: {
                  type: type,
                  unionid: wx.getStorageSync('openid'),
                  sign: sign
                },
                method: 'POST',
                header: {
                  'content-type': 'application/json'
                },
                success: function (res) {
                  var awardIndex = res.data.content.lindex - 1;
                  console.log(awardIndex)
                  var runNum = 7; //转的圈数
                  //旋转角度
                  that.runDeg = that.runDeg || 0;
                  that.runDeg = that.runDeg + (360 - that.runDeg % 360) + (360 * runNum - awardIndex * (360 / 10))
                  //创建动画
                  var animationRun = wx.createAnimation({
                    duration: 4000,
                    timingFunction: 'ease'
                  })
                  animationRun.rotate(that.runDeg).step();
                  that.setData({
                    animationData: animationRun.export(),
                  })
                  //中奖提示
                  var awardsConfig = that.awardsConfig;
                  setTimeout(function () {
                    if (awardIndex == 0) {
                      that.setData({
                        losedialog: false,
                      })
                    } else {
                      that.setData({
                        windialog: false,
                        winner: awardsConfig.awards[awardIndex].name,
                        home_content:true
                      })
                    }
                  }.bind(this), 4000)
                }
              })
            } else if (res.cancel) {
              that.setData({
                disabled: false,
              })
            }
          }
        })
      })
    }
  },
  onHide: function() {
    this.setData({
      disabled: false,
    })
    app.globalData.scene = 1001;
  },
  stopTouchMove: function() {
    return false;
  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    let that = this;
    wx.showNavigationBarLoading() //在标题栏中显示加载
    that.onShow(); // 刷新页面
    wx.hideNavigationBarLoading() //完成停止加载
    wx.stopPullDownRefresh() //停止下拉刷新
  },
  gotorecord: function() {
    wx.navigateTo({
      url: '/pages/main/winRecord/index',
    })
  },
  getchance: function() {
    const that = this;
    that.setData({
      freechou: true,
    })
    var object = {
      unionid: wx.getStorageSync('openid'),
      block: 5,
      ad_id: that.data.ad_auth
    }
    var sign = app.sort_ASCII(object)
    wx.request({
      url: app.globalData.new_url + '/adauth/Adv/get_ad',
      data: {
        unionid: wx.getStorageSync('openid'),
        block: 5,
        ad_id: that.data.ad_auth,
        sign:sign
      },
      method: 'POST',
      header: {
        'content-type': 'application/json'
      },
      success: function(res) {
        console.log(res)
        if (res.data.content.way == 1) {
          that.setData({
            nochance: false,
            ad_data: res.data.content
          })
        } else {
          that.setData({
            ad_data: res.data.content
          })
          var ad_id = res.data.content.ad_id;
          wx.navigateTo({
            url: '../../other/erweima/index?ad_id=' + ad_id + '&&plate=5',
          })
        }
      }
    })
  },
  navigateTo: function(e) {
    const that = this;
    const ad_data = that.data.ad_data;
    const ad_id = ad_data.ad_id;
    if (ad_data.way == 1) {
      wx.navigateToMiniProgram({
        appId: ad_data.appid,
        path: ad_data.path,
        envVersion: 'develop',
        success(res) {
          var object = {
            unionid: wx.getStorageSync('openid'),
            type: 1,
            ad_id: ad_id,
            plate: 5,
          }
          var sign = app.sort_ASCII(object)
          wx.request({
            url: app.globalData.new_url + '/adauth/Adv/back_adv',
            data: {
              unionid: wx.getStorageSync('openid'),
              type: 1,
              ad_id: ad_id,
              plate: 5,
              sign:sign
            },
            method: 'POST',
            header: {
              'content-type': 'application/json'
            },
            success: function(res) {
              console.log('跳转成功', res)
              that.setData({
                nochance: true,
                losedialog: true,
                windialog: true,
                disabled: false,
              })
              that.data.flow = true;
            }
          })
        }
      })
    } else {
      wx.navigateTo({
        url: '../../other/erweima/index?ad_id=' + ad_id + '&&plate=5',
      })
      that.setData({
        nochance: true,
        windialog: true,
      })
    }
  },
  continueplay: function() {
    const that = this;
    const ad_data = that.data.ad_data;
    const ad_id = ad_data.ad_id;
    if (ad_data.way == 1){
      that.setData({
        nochance: false,
      })
    }else{
      wx.navigateTo({
        url: '../../other/erweima/index?ad_id=' + ad_id + '&&plate=5',
      })
      that.setData({
        clickedfail:false,
        tryfail:true
      })
    }
  },
  hideHandle: function() {
    const that = this;
    that.setData({
      losedialog: true,
      windialog: true,
      disabled: false,
      freechou: true,
      nochance: true,
    },()=>{
      if (interstitialAd) {
        interstitialAd.show().catch((err) => {
          console.error(err)
        })
      }
    })
    that.data.flow = false;
    that.onShow();
  },
  hideHandles: function() {
    const that = this;
    that.setData({
      tryfail: true,
      clickedfail: false,
    })
  },
})